package com.runachina.runa;

import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.runachina.R;
import com.runachina.common.BaseActivity;
import com.runachina.common.CompanyActivity;
import com.runachina.java.SendDataAnalysis;
import com.runachina.java.TcpSocket;

import java.util.Timer;
import java.util.TimerTask;

public class FlowActivity extends BaseActivity implements OnClickListener{

    private RadioGroup point;
    private RadioButton point4,point5;
    private int manyPoint=4;//当前选取的是多少点

    public  static EditText row11,row12,row13,row14,row15;
    private EditText row21,row22,row23,row24,row25;
    public  static  EditText row31,row32,row33,row34,row35;
    private EditText inNum;


    private Button btnread,btncalcu,btnset;

    private TextView sendtitle,sendtext;
    public  static TextView rcvtext,rcvbyte;


    private byte [] readFlow = {(byte) 0xfe,(byte) 0xfe, (byte) 0xfe,(byte) 0xfe,(byte) 0xfe,
            0x68, 0x20,
            (byte) 0xAA,(byte) 0xAA,(byte) 0xAA,(byte) 0xAA,(byte) 0xAA,
            0x11, 0x11, 0x01, 0x03,(byte) 0x3f,(byte) 0x90,0x12,
            (byte) 0xe1,0x16,
            (byte) 0x00,(byte) 0x16};

    public  static byte [] setFourFlow = {(byte) 0xfe,(byte) 0xfe,(byte) 0xfe, (byte) 0xfe,(byte) 0xfe,
            0x68, 0x20,
            (byte) 0xAA,(byte) 0xAA,(byte) 0xAA,(byte) 0xAA,(byte) 0xAA,(byte) 0xAA,(byte) 0xAA,
            0x36, (byte) 0x0C,(byte) 0xA0,0x19,(byte) 0x88, 0x00,
            (byte) 0x00,(byte) 0x00,(byte) 0x00,(byte) 0x00,(byte) 0x00,(byte) 0x00,(byte) 0x00,(byte) 0x00,
            (byte) 0x00,0x16,
            (byte) 0x00,0x16};

    public  static byte [] setFiveFlow = {(byte) 0xfe,(byte) 0xfe,(byte) 0xfe, (byte) 0xfe,(byte) 0xfe,
            0x68, 0x20,
            (byte) 0xAA,(byte) 0xAA,(byte) 0xAA,(byte) 0xAA,(byte) 0xAA,(byte) 0xAA,(byte) 0xAA,
            0x36, (byte) 0x0E,(byte) 0xA0,0x19,(byte) 0x88, 0x00,
            (byte) 0x00,(byte) 0x00,(byte) 0x00,(byte) 0x00,(byte) 0x00,(byte) 0x00,(byte) 0x00,(byte) 0x00,
            (byte) 0x00,(byte) 0x00,
            (byte) 0x00,0x16,
            (byte) 0x00,0x16};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ac_flow);

        set_toolbar("流量补偿", "");

        set_leftmenu(FlowActivity.this);

        init_view();

        hideSendText(sendtitle,sendtext);

        inWhichAc="runa.FlowActivity" ;
    }

    /**
     * 初始化界面控件
     */
    void init_view(){

        inNum=(EditText)findViewById(R.id.inputnum);

        point =(RadioGroup) findViewById(R.id.point);
        point4 =(RadioButton) findViewById(R.id.point4);
        point4.setOnClickListener(this);
        point5 =(RadioButton) findViewById(R.id.point5);
        point5.setOnClickListener(this);

        row11 =(EditText)findViewById(R.id.row11);
        row12 =(EditText)findViewById(R.id.row12);
        row13 =(EditText)findViewById(R.id.row13);
        row14 =(EditText)findViewById(R.id.row14);
        row15 =(EditText)findViewById(R.id.row15);

        row21 =(EditText)findViewById(R.id.row21);
        row22 =(EditText)findViewById(R.id.row22);
        row23 =(EditText)findViewById(R.id.row23);
        row24 =(EditText)findViewById(R.id.row24);
        row25 =(EditText)findViewById(R.id.row25);

        row31 =(EditText)findViewById(R.id.row31);
        row32 =(EditText)findViewById(R.id.row32);
        row33 =(EditText)findViewById(R.id.row33);
        row34 =(EditText)findViewById(R.id.row34);
        row35 =(EditText)findViewById(R.id.row35);

        sendtitle=(TextView)findViewById(R.id.sendtitle);
        sendtext=(TextView)findViewById(R.id.sendtext);
        rcvtext =(TextView)findViewById(R.id.rcvtext);
        rcvbyte =(TextView)findViewById(R.id.rcvbyte);

        btnread=(Button)findViewById(R.id.btnread);
        btnread.setOnClickListener(btnreadFun);
        btncalcu=(Button)findViewById(R.id.btncalcu);
        btncalcu.setOnClickListener(btncalcuFun);
        btnset=(Button)findViewById(R.id.btnset);
        btnset.setOnClickListener(btnsetFun);
    }
    private void clear_textDisplay(){
        sendtext.setText("");
        rcvtext.setText("");
        rcvbyte.setText("");
        startTimer(TI);
    }

    View.OnClickListener btnreadFun =new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            clear_textDisplay();
            inWhichAc="runa.FlowActivity.read" ;
            //获取完整的发送sendbyte[]
            String meterNum=inNum.getText().toString();
            byte[] sendbyte= SendDataAnalysis.flowRead(readFlow,meterNum);
            //显示发送报文
            sendtext.setText(byteToHexString(sendbyte));
            //发送sendbyte[]
            String sendResult = TcpSocket.wifiSendByte(sendbyte);
//            new Timer().schedule(new TimerTask() {
//                @Override
//                public void run() {
//                    TcpSocket.receServerMessage();
//                }
//            },3000);

        }
    };
    View.OnClickListener btncalcuFun =new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //clear_textDisplay();
            double value11 =Double.parseDouble(row11.getText().toString()+"0");
            double value12 =Double.parseDouble(row12.getText().toString()+"0");
            double value13 =Double.parseDouble(row13.getText().toString()+"0");
            double value14 =Double.parseDouble(row14.getText().toString()+"0");

            String value15Str =row15.getText().toString().equals("null") ? "0.0" :row15.getText().toString() ;
            double value15 =Double.parseDouble(value15Str+"0");

            double value21=0.0;
            double value22=0.0;
            double value23=0.0;
            double value24=0.0;
            double value25=0.0;
            try {
                value21 =Double.parseDouble(row21.getText().toString());
                value22 =Double.parseDouble(row22.getText().toString());
                value23 =Double.parseDouble(row23.getText().toString());
                value24 =Double.parseDouble(row24.getText().toString());
                value25 =Double.parseDouble(row25.getText().toString());
            }catch (Exception e){
                show("当前误差输入错误!");
            }
            String value31 =(double)(((int)((value11+value21)*1000))/1000.0)+"";
            String value32 =(double)(((int)((value12+value22)*1000))/1000.0)+"";
            String value33 =(double)(((int)((value13+value23)*1000))/1000.0)+"";
            String value34 =(double)(((int)((value14+value24)*1000))/1000.0)+"";
            String value35 =(double)(((int)((value15+value25)*1000))/1000.0)+"";

            row31.setText(value31);
            row32.setText(value32);
            row33.setText(value33);
            row34.setText(value34);
            row35.setText(value35);

        }
    };
    View.OnClickListener btnsetFun =new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            clear_textDisplay();
            inWhichAc="runa.FlowActivity.set" ;
            //获取发送报文
            byte[] sendbyte=  getSetFlowBaowen();
           //显示发送报文
            sendtext.setText(byteToHexString(sendbyte));
            //发送sendbyte[]
            String sendResult = TcpSocket.wifiSendByte(sendbyte);
//            new Timer().schedule(new TimerTask() {
//                @Override
//                public void run() {
//                    TcpSocket.receServerMessage();
//                }
//            },3000);

        }
    };


    /**
     * 设置流量修正：获取报文
     * @return
     */
    private byte[] getSetFlowBaowen(){

        String meterNum=inNum.getText().toString();

        if(manyPoint==4){
            byte[] sendbyte= SendDataAnalysis.flowSet(setFourFlow,meterNum,manyPoint,
                    getFlowValue(row31), getFlowValue(row32), getFlowValue(row33), getFlowValue(row34), getFlowValue(row35));

            return sendbyte;
        }else{
            byte[] sendbyte= SendDataAnalysis.flowSet(setFiveFlow,meterNum,manyPoint,
                    getFlowValue(row31), getFlowValue(row32), getFlowValue(row33), getFlowValue(row34), getFlowValue(row35));
            return sendbyte;
        }
    }



    private double getFlowValue(EditText edt){
        double value=0.0 ;
        try {
            value = Double.valueOf(edt.getText().toString());
        }catch (Exception e){};

        return value;

    }

    /**
     * RadioButton
     * @param v
     */
    @Override
    public void onClick(View v) {
        if(v.getId()==R.id.point5){
            manyPoint=5;
            row15.setVisibility(View.VISIBLE);
            row25.setVisibility(View.VISIBLE);
            row35.setVisibility(View.VISIBLE);}
        if(v.getId()==R.id.point4){
            manyPoint=4;
            row15.setVisibility(View.GONE);
            row25.setVisibility(View.GONE);
            row35.setVisibility(View.GONE);}

    }

    /**
     * Toolbar中的Menu菜单项
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }
    /**
     * Activity创建时候会执行一次，所以可以用来初始化toolbar中的wifi图标
     * @return
     */
    public boolean onPrepareOptionsMenu(Menu menu) {
        super.onPrepareOptionsMenu(menu);

        MenuItem menuItem = menu.findItem(R.id.menu_connect);
        //wifi connect，返回当前连接状态
        String connectResult= TcpSocket.readConnect();
        if((connectResult.equals("连接成功!"))||connectResult.equals("已经连接!")){
            menuItem.setTitle("connect!");
            menuItem.setIcon(R.drawable.wifi_connect);
        }else{
            menuItem.setTitle("no connect!");
            menuItem.setIcon(R.drawable.wifi_noconnect);
        }
        return true;
    }
    private MenuItem me;
    private int type=0;
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        me=item;
        System.out.println("onOptionsItemSelected");

        switch (item.getItemId()){
            case R.id.menu_connect:
                String connectResult= TcpSocket.wificonnect();//wifi connect
                show(connectResult);//TOast connect result
                if((connectResult.equals("连接成功!"))||connectResult.equals("已经连接!")){
                    item.setTitle("connect!");
                    item.setIcon(R.drawable.wifi_connect);
                }else{
                    item.setTitle("no connect!");
                    item.setIcon(R.drawable.wifi_noconnect);
                    new Timer().schedule(new TimerTask() {
                        @Override
                        public void run() {
                            goWifiSetting();
                            type=1;
                        }
                    },1000);
                }
                return true;
            case R.id.menu_choice:
                intent = new Intent(FlowActivity.this, CompanyActivity.class);
                startActivity(intent);
                finish();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
    //每次进来判断是否是从设置wifi页面进来的，如果是，重新连接socket，判断是否可用
    @Override
    protected void onResume() {
        super.onResume();
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                type=0;
                String connectResult = TcpSocket.wificonnect();//wifi connect
                //show(connectResult);//TOast connect result
                if (isWifi()) {
                    if (me != null) {
                        if ((connectResult.equals("连接成功!")) || connectResult.equals("已经连接!")) {

                            me.setTitle("connect!");
                            me.setIcon(R.drawable.wifi_connect);
                        } else {

                            me.setTitle("no connect!");
                            me.setIcon(R.drawable.wifi_noconnect);
                        }
                    }
                } else {
                    if (me!=null){
                        me.setTitle("no connect!");
                        me.setIcon(R.drawable.wifi_noconnect);
                    }

                }
            }
        });
    }
    /**
     * 设置back监听
     */
    @Override
    public void onBackPressed() {
        exitApp();
    }
}
